package com.usian.common.exception;

import com.usian.model.common.dtos.ResponseResult;
import lombok.extern.log4j.Log4j2;
import org.apache.hbase.thirdparty.com.google.common.collect.ImmutableMap;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice //controller的增强类  通知类
@Log4j2
public class ExceptionCatch {

    //使用EXCEPTIONS存放异常类型和错误代码的映射，ImmutableMap的特点的一旦创建不可改变，并且线程安全
    private static ImmutableMap<Class<? extends Throwable>, ResponseResult> EXCEPTIONS;
    //使用builder来构建一个异常类型和错误代码的异常
    protected static ImmutableMap.Builder<Class<? extends Throwable>,ResponseResult> builder = ImmutableMap.builder();



    //抓取可预知异常(自定义)
    @ExceptionHandler(CostomException.class)
    @ResponseBody
    public ResponseResult exception(CostomException exception){
        return exception.getResponseResult();
    }


    //抓取不可预知异常(自定义)
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult exceptions(Exception exception){
        log.error(exception.getMessage());
        exception.printStackTrace();
        //如果Map集合中有对应的异常类型 就返回对应的数据 如果没有 则返回99999
        if(EXCEPTIONS == null){
            //先初始化
            EXCEPTIONS = builder.build();
        }
        //直接取
        ResponseResult responseResult = EXCEPTIONS.get(exception.getClass());
        if(responseResult==null){
            return new ResponseResult(99999,"出现重大问题，请联系管理员");
        }else{
            return responseResult;
        }

    }


    static{
        //在这里加入一些基础的异常类型判断
        builder.put(HttpMessageNotReadableException.class,ResponseResult.errorResult( 1,"非法参数"));
        builder.put(NullPointerException.class,ResponseResult.errorResult(1,"出现空对象异常"));
        builder.put(IndexOutOfBoundsException.class,ResponseResult.errorResult(1,"下角标越界异常"));
        //自己填充的
        builder.put(ArithmeticException.class,ResponseResult.errorResult(1,"除数不能为0"));
    }

}
